import random
import math
from PIL import Image
import numpy as np

class CaptchaClass():
    def __init__(self,targetWidth,targetHeight,circleR,r1):
        self.targetWidth=targetWidth
        self.targeHeight=targetHeight
        self.circleR=circleR
        self.r1=r1
    def getBlockData(self):
        """ 生成小图片 """
        data=[[0 for i in range(self.targetWidth)] for i in range(self.targetWidth)]   
        x2 = self.targetWidth -self.circleR
        h1 = self.circleR + random.random() * (self.targetWidth-3*self.circleR-self.r1)
        po = math.pow(self.circleR,2)
        xbegin = self.targetWidth - self.circleR - self.r1
        ybegin = self.targeHeight- self.circleR - self.r1 
        # //圆的标准方程 (x-a)²+(y-b1)²=r²,标识圆心（a,b）,半径为r的圆
        # //计算需要的小图轮廓，用二维数组来表示，二维数组有两张值，0和1，其中0表示没有颜色，1有颜色
        for i in range(0,self.targetWidth):
            for  j in range(0,self.targeHeight):
                d2 = math.pow(j - 2,2) + math.pow(i - h1,2)
                d3 = math.pow(i - x2,2) + math.pow(j - h1,2)                
                if (j <= ybegin and d2 < po)or(i >= xbegin and d3 > po):
                    
                    data[i][j] = 0
                else: 
                    data[i][j] = 255
        return data; 
    def savaBgblock(self):
        data1=self.getBlockData()
        data_list1=np.asarray(data1)
       
       
        pic=Image.fromarray(data_list1.astype(np.uint8))
        
        pic=Image.fromarray(data_list1,mode='RGBA')
        im1 = pic.resize((self.targetWidth,self.targetWidth), Image.BILINEAR)
        im1.save('random_generate_pic.png')
            
       



# Todo 测试 是否 符合要求
if __name__=="__main__":    
    targetWidth = 55;#小图长
    targetHeight = 45;#小图宽
    circleR = 8;#半径
    r1 = 2;#距离点
    
    imgconfig=CaptchaClass(targetWidth,targetHeight,circleR,r1)
    imgconfig.savaBgblock()
